package com.example.process_bar

import android.os.*
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import android.widget.ProgressBar
import android.widget.Toast
import androidx.annotation.RequiresApi
import java.util.concurrent.TimeUnit
import kotlin.random.Random

class MainActivity : AppCompatActivity() {

    //当前进度
    private var curProgress: Int = 0
    private val OK: Int = 100

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val progressBar = findViewById<ProgressBar>(R.id.progress_horizontal1)
        //进度条的动态实现需要另外创建一个线程去执行，不支持在该主线程中操作该进度条的进度
        //使用安卓提供的handler来实现
        val handler = object : Handler() {
            @RequiresApi(Build.VERSION_CODES.N)
            override fun handleMessage(msg: Message) {
                if (msg.what == 0x1111) {
                    progressBar.setProgress(curProgress)
                    return
                }
                Toast.makeText(this@MainActivity, "操作耗时已完成!", Toast.LENGTH_SHORT).show()
                //让进度条消失
                progressBar.visibility = View.GONE
            }
        }
        //创建一个单独的线程去处理耗时操作
        Thread {
            while (true) {
                doWork()
                val message = Message()
                if (curProgress < OK) {
                    //设置消息代码
                    message.what = 0x1111
                    //发送消息
                    handler.sendMessage(message)
                } else {
                    //进度已完成
                    message.what = 0x110
                    handler.sendMessage(message)
                    break
                }
            }
        }.start()


    }

    /**
     * 进度完成情况
     */
    private fun doWork(): Unit {
        curProgress = curProgress.plus(Random.nextInt(30))
        TimeUnit.SECONDS.sleep(1)
    }


}
